<template>
  <div>
    <a-row :gutter="16">
      <a-collapse default-active-key="1" expandIconPosition="right" style="margin-bottom: 10px; border: 1px solid #e8e8e8;">
        <a-collapse-panel key="1" header="采购订单信息">
          <div>
            <a-descriptions>
              <a-descriptions-item label="订单编码">{{ orderInfo.code }}</a-descriptions-item>
              <a-descriptions-item label="供应商名称">{{ orderInfo.supplierName }}</a-descriptions-item>
              <a-descriptions-item label="税率">{{ orderInfo.taxRate }}%</a-descriptions-item>
              <a-descriptions-item label="含税总额">{{ orderInfo.totalTaxPrice }}</a-descriptions-item>
              <a-descriptions-item label="签订时间">{{ orderInfo.signDate }}</a-descriptions-item>
              <a-descriptions-item label="交付时间">{{ orderInfo.deliveryTime }}</a-descriptions-item>
              <a-descriptions-item label="采购数">{{ orderInfo.totalQty }}</a-descriptions-item>
              <a-descriptions-item label="到货数">{{ orderInfo.totalStorageQty }}</a-descriptions-item>
              <a-descriptions-item label="交付地址">{{ orderInfo.deliveryAddress }}</a-descriptions-item>
              <a-descriptions-item label="备注">{{ orderInfo.remark }}</a-descriptions-item>
            </a-descriptions>
          </div>
          <a-tag :color="orderInfo.status === 'PARTIAL' ? 'orange' : orderInfo.status === 'FINISHED' ? 'green' : 'blue'" slot="extra">{{ orderInfo.statusStr }}</a-tag>
        </a-collapse-panel>
      </a-collapse>
    </a-row>
    <a-row :gutter="16">
      <a-card :bordered="false" :bodyStyle="tstyle" title="到货入库作业">
        <div>
          <scan ref="scan" @sure="handleScanSure"/>
        </div>
      </a-card>
      <a-card :bordered="false">
        <a-table
          :columns="orderItemColumns"
          :dataSource="orderItemData"
          bordered
          :scroll="{x: 1500}"
          size="small"
          :rowKey="(record) => record.id"
          :pagination="false"
        >
          <span slot="storageQtySlots" slot-scope="text, record">
            {{ text }} <a-tag v-if="record.child.num > 0" color="red">+{{ record.child.num }}</a-tag>
          </span>
          <div slot="scanDataSlots" slot-scope="text, record">
            <div style="margin-bottom: 2px;float: left;width: 100%;" :key="index" v-for="(item, index) in record.child.items">
              <div v-if="item.qty > 0">
                <a-tag color="orange" closable style="text-align: left;float: left;" @close="delBarcode(record.materialCode, item)">
                  <span style="font-size: 14px;padding-right: 6px;">{{ item.barcode }}</span> <a-badge :count="item.qty"/>
                </a-tag>
              </div>
            </div>
          </div>
        </a-table>
      </a-card>
    </a-row>
    <footer-tool-bar>
      <div style="display: inline-block;padding: 0 20px;">
        <span style="font-weight: bold;font-size: 14px;">到货总数：</span>
        <span style="font-weight: bold;font-size: 18px;color: red;"><span>{{ totalQty }}</span></span>
      </div>
      <a-button class="subButton" @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleSubmit" :loading="loading">提交</a-button>
    </footer-tool-bar>
  </div>
</template>
<script>
  import FooterToolBar from '@/components/FooterToolbar'
  import { purchaseOrderDetail, purchaseOrderPage } from '@/api/modular/main/order/purchase/purchaseOrderManage'
  import { storagePurchaseAdd } from '@/api/modular/main/storage/purchase/storagePurchaseManage'
  import scan from './scan.vue'
  import BigNumber from 'bignumber.js'
  export default {
    components: {
      scan,
      BigNumber,
      FooterToolBar
    },
    data () {
      return {
        loading: false,
        totalQty: 0,
        queryParam: {},
        orderMaterialCodes: [],
        orderItemData: [],
        orderInfo: {
          id: '',
          code: '',
          companyName: '',
          customerName: '',
          deliveryAddress: '',
          deliveryTime: '',
          remark: '',
          signDate: '',
          signPlace: '',
          status: '',
          statusStr: '',
          taxRate: '',
          totalTaxPrice: ''
        },
        orderItemColumns: [
          {
            title: '物料编码',
            dataIndex: 'materialCode',
            align: 'center',
            width: 200,
            scopedSlots: { customRender: 'materialCode' }
          },
          {
            title: '物料名称',
            dataIndex: 'materialName',
            align: 'center',
            width: 200,
            scopedSlots: { customRender: 'materialName' }
          },
          {
            title: '物料型号',
            dataIndex: 'materialModel',
            align: 'center',
            width: 300,
            scopedSlots: { customRender: 'materialModel' }
          },
          {
            title: '已到货数',
            dataIndex: 'storageQty',
            align: 'center',
            width: 100,
            scopedSlots: { customRender: 'storageQtySlots' }
          },
          {
            title: '总数',
            dataIndex: 'qty',
            align: 'center',
            width: 100,
            scopedSlots: { customRender: 'qty' }
          },
          {
            title: '单价(￥)',
            dataIndex: 'unitPrice',
            align: 'center',
            width: 100,
            scopedSlots: { customRender: 'unitPrice' }
          },
          {
            title: '单位',
            dataIndex: 'unit',
            align: 'center',
            width: 80,
            scopedSlots: { customRender: 'unit' }
          },
          {
            title: '小计(￥)',
            dataIndex: 'amount',
            align: 'center',
            width: 120,
            scopedSlots: { customRender: 'amount' }
          },
          {
            title: '货期',
            dataIndex: 'deliveryDate',
            align: 'center',
            width: 150,
            scopedSlots: { customRender: 'deliveryDate' }
          },
          {
            title: '条码信息',
            dataIndex: 'child',
            align: 'center',
            width: 300,
            scopedSlots: { customRender: 'scanDataSlots' },
            fixed: 'right'
          }
        ],
        tstyle: { 'padding-bottom': '0px', 'margin-bottom': '10px' },
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return purchaseOrderPage(Object.assign(parameter, this.queryParam)).then((res) => {
            return res.data
          })
        },
        statusData: [],
        selectedRowKeys: [],
        selectedRows: []
      }
    },
    created () {
      const statusOption = this.$options
      this.statusData = statusOption.filters['dictData']('purchaseorder_status')
    },
    activated () {
      const oldCode = this.orderInfo.code
      this.orderInfo.code = this.$route.query.code
      if (oldCode !== this.orderInfo.code) {
        this.reloadPage()
      }
    },
    methods: {
      reloadPage () {
        this.totalQty = 0
        this.resetScanBarcodes()
        purchaseOrderDetail(this.orderInfo.code).then((res) => {
          if (res.success) {
            this.orderItemData = res.data.itemList
            this.orderInfo.code = res.data.code
            this.orderInfo.companyName = res.data.companyName
            this.orderInfo.supplierName = res.data.supplierName
            this.orderInfo.deliveryAddress = res.data.deliveryAddress
            this.orderInfo.deliveryTime = res.data.deliveryTime
            this.orderInfo.remark = res.data.remark
            this.orderInfo.signDate = res.data.signDate
            this.orderInfo.status = res.data.status
            this.orderInfo.statusStr = this.statusData.find(item => res.data.status === item.code).name
            this.orderInfo.taxRate = res.data.taxRate
            this.orderInfo.totalTaxPrice = '￥' + res.data.totalTaxPrice
            this.orderInfo.totalQty = res.data.totalQty
            this.orderInfo.totalStorageQty = res.data.totalStorageQty
            this.orderInfo.unit = res.data.unit

            this.orderItemData.forEach(item => {
              item.child = {
                num: 0,
                items: []
              }
              this.orderMaterialCodes.push(item.materialCode)
            })
            this.$refs.scan.add(this.orderMaterialCodes)
          } else {
            this.$message.error('数据加载失败:' + res.message)
          }
        })
      },
      handleScanSure (data) {
        const newData = [...this.orderItemData]
        const orderItem = newData.find(item => item.materialCode === data.materialCode)
        if (orderItem) {
          orderItem.child.num = BigNumber(orderItem.child.num).plus(BigNumber(data.qty))
          orderItem.child.items.push(
            {
              barcode: data.barcode,
              qty: data.qty,
              barcodeType: data.barcodeType
            }
          )
          orderItem.child.items = orderItem.child.items.reverse()
          this.orderItemData = newData
        }
        this.countScanItemQty()
      },
      countScanItemQty () {
        var total = BigNumber(0)
        this.orderItemData.forEach(item => {
          total = total.plus(BigNumber(item.child.num))
        })
        this.totalQty = total
      },
      resetScanBarcodes () {
        this.$refs.scan.clearBarcodes()
      },
      delBarcode (materialCode, target) {
        const newData = [...this.orderItemData]
        const record = newData.find(item => item.materialCode === materialCode)
        if (record) {
            const newItems = [...record.child.items]
          for (var i in newItems) {
            if (newItems[i].barcode === target.barcode) {
              record.child.num = record.child.num - target.qty
              newItems.splice(i, 1, {
                barcode: '',
                qty: 0,
                barcodeType: 0
              })
              record.child.items = newItems
              this.orderItemData = newData
              this.$refs.scan.removeScanedBarcode(target.barcode)
              this.countScanItemQty()
            }
          }
        }
      },
      handleCancel () {
        this.$multiTab.closeAndOpen('/purchaseOrder')
      },
      handleSubmit () {
        const storageData = {
          purchaseOrderCode: this.orderInfo.code,
          itemList: []
        }
        const records = this.orderItemData.filter(item => item.child.num > 0)
        if (records && records.length > 0) {
          for (var record of records) {
            for (var item of record.child.items) {
              if (item.qty > 0) {
                storageData.itemList.push(
                  {
                    'barcode': item.barcode,
                    'barcodeType': item.barcodeType,
                    'materialCode': record.materialCode,
                    'materialName': record.materialName,
                    'materialModel': record.materialModel,
                    'qty': item.qty,
                    'unit': record.unit
                  }
                )
              }
            }
          }
          this.loading = true
          storagePurchaseAdd(storageData).then((res) => {
              if (res.success) {
                this.$message.success('保存成功')
                this.loading = false
                this.reloadPage()
                setTimeout(() => {
                  this.handleCancel()
                }, 100)
              } else {
                this.$message.error('保存失败:' + res.message)
              }
            }).finally((res) => {
              this.loading = false
            })
        } else {
          this.$message.error('无数据需要入库,提交失败！')
        }
      }
    }
  }
</script>
<style lang="less">
  .table-operator {
    margin-bottom: 18px;
  }
  button {
    margin-right: 8px;
  }
  .ant-collapse {
    background-color: #fff;
  }
  .ant-collapse-header {
    font-size: 16px;
  }
  .ant-collapse-content {
    overflow: hidden;
    color: rgba(0, 0, 0, 0.65);
    background-color: #fff;
    border-top: 1px solid #e8e8e8;
  }
</style>
